#!/usr/bin/python
# -*- coding: utf8 -*-

import logging

from pymylib.lib.base import *
from pymylib.model import Session, Category
from pylons.templating import render, render_response
from __init__ import perPage


class CategoryController(BaseController):
    template_prefix = '/category'
    template_err_prefix = '/error'
    
    def __before__(self):
        if 'user' in session:
            if session['user'] == 'anonymous':
                session['path_before_login'] = request.path_info
                session.save()
                return redirect_to(h.url_for(controller='login'))
        else: return redirect_to(h.url_for(controller='login'))

    def __check_permitions__(self):
        """Check for permitions"""

        # Зарегистрирован-ли пользователь в системе?
        if self.requires_auth and session['user'] == 'anonymous':
            c.error = "Необходимо выполнить вход в систему!"
            return False
        
        if session['librarianUser'] or session['adminAccess']:
            return True
        else: c.error = "Нет прав на выполнение этой операции!"

    def index(self):
        redirect_to(action='list')

    def list(self):
        c.pageTitle = unicode('Классификатор жанров', encoding='utf8')
        c.formCaption = c.pageTitle
        c.curPage = 0

        try:
            cat_q = Session.query(Category)
            c.curPage = int(request.params['pg'])-1
            c.category = list(cat_q.all()[perPage*c.curPage:perPage*(c.curPage+1)])
        except:
            #c.category = list(cat_q.filter_by(id <> -1).limit(perPage))
            c.category = list(cat_q.limit(perPage))

        ''' Получим страницы с диапазоном заданным perPage '''
        c.pages = []
        i = 0
        for cat in c.category[:int(cat_q.count()/perPage)+1]:
            i = i+1
            c.pages.append(i)
        
        if len(c.pages) == 1:
            c.pages = None

        ''' ---------------------------------------------- '''
        c.currentUser = None
        c.user_id = session['user_id']
        c.user_name = session['fio']
            
        return render_response(self.template_prefix + '/list.myt')

    def fullview(self, id):
        cat_q = Session.query(Category)
        c.category = cat_q.get_by(id=id)

        return render_response(self.template_prefix + '/fullinfo.myt')


    def edit(self, id):
        # Проверка прав на выполнение данного действия
        if self.__check_permitions__() != True:
            c.index = 'fullview'+id
            return render(self.template_err_prefix + '/error.mako')

        cat_q = Session.query(Category)
        c.category = cat_q.get_by(id=id)

        return render_response(self.template_prefix + '/edit.myt')

    def update(self, id):
        # Проверка прав на выполнение данного действия
        if self.__check_permitions__() != True:
            c.index = 'fullview'+id
            return render(self.template_err_prefix + '/error.mako')

        cat_q = Session.query(Category)
        cat_obj = cat_q.get_by(id=id)

        if request.params['name'] == "": raise
        else: cat_obj.name = request.params['name']

        if request.params['note'] == "": cat_obj.note = None
        else: cat_obj.note = request.params['note']

        try:
            Session.commit()
        except:
            Session.rollback()
            raise
        
        redirect_to('../list')
        
    def add(self):
        # Проверка прав на выполнение данного действия
        if self.__check_permitions__() != True:
            c.index = 'add'
            return render(self.template_err_prefix + '/error.mako')

        c.category = None

        return render_response(self.template_prefix + '/edit.myt')

    def create(self):
        # Проверка прав на выполнение данного действия
        if self.__check_permitions__() != True:
            c.index = 'add'
            return render(self.template_err_prefix + '/error.mako')

        new_category = Category()

        if request.params['name'] == "": raise
        else: new_category.name = request.params['name']

        if request.params['note'] == "": new_category.note = None
        else: new_category.note = request.params['note']

        try:            
            Session.save(new_category)
            Session.commit()
        except:
            Session.rollback()
            raise
        
        redirect_to('list')

    def delete(self, id):
        # Проверка прав на выполнение данного действия
        if self.__check_permitions__() != True:
            c.index = 'fullview'+id
            return render(self.template_err_prefix + '/error.mako')

        cat_q = Session.query(Category)
        cat_obj = cat_q.get_by(id=id)
        
        try:
            Session.delete(cat_obj)
            Session.commit()
        except:
            Session.rollback()
            raise
        redirect_to('../list')
